package cn.kgc.controller;

import cn.kgc.entity.User;
import cn.kgc.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user")
    public String getAllUser(Model model) {
        model.addAttribute("userList", userService.getAllUser());
        return "userList";
    }
    @GetMapping("/user/view")
    public String toUserView(Model model){
        model.addAttribute("user",new User());
        return "user";
    }
    @GetMapping("/user/count/{name}")
    @ResponseBody
    public  Map countByName(@PathVariable("name") String name){
        Integer count     =userService.countByName(name);
        Map<String,Object> data = new HashMap<>();
        data.put("count",count);
        return data;
    }

    @GetMapping("/user/{pageNO}/{pageSize}")
    public String getUserList(@PathVariable("pageNO") Integer pageNO,
                              @PathVariable("pageSize") Integer pageSize,
                              Model model){
        model.addAttribute("userList",userService.getUserList(pageNO,pageSize));
        model.addAttribute("pageNO",pageNO);
        model.addAttribute("pageSize",pageSize);
/*        log.debug("XXXXXxxxxxxxxxX");*/
        return "userList";
    }




    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") Integer id){
        return userService.getUserById(id);
    }
    @PostMapping("/user")
    public User addUser(@RequestBody User user){
        userService.addUser(user);
        return user;
    }
}

